package queue_stack.leetcode.medium;

import java.util.ArrayList;
import java.util.List;

/**
 * @author bruin_du
 * @description 往完全二叉树添加节点
 * @date 2022/8/13 23:23
 **/
public class OfferII043_CBTInserter {
    List<TreeNode> list;
    public OfferII043_CBTInserter(TreeNode root) {
        list = new ArrayList<>();
        list.add(root);
        for (int i = 0; i < list.size(); i++){
            TreeNode node = list.get(i);
            if (node.left != null) list.add(node.left);
            if (node.right != null) list.add(node.right);
        }
    }

    public int insert(int v) {
        TreeNode node = list.get((list.size() - 1) / 2);
        TreeNode newNode = new TreeNode(v);
        if (node.left == null) {
            node.left = newNode;
        } else {
            node.right = newNode;
        }
        list.add(newNode);
        return node.val;
    }

    public TreeNode get_root() {
        return list.get(0);
    }
}
